import React from 'react'
import { Modal, Alert } from 'antd'
import PropTypes from 'prop-types'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import moment from 'moment'
import { ExclamationCircleOutlined } from '@ant-design/icons'
import { addWindow } from '@redux/actions'
import Approve from '@components/ApprovePre/Index'
import SecretaryHistory from './RegisterCase/SecretaryHistory'
import SecretaryInput from './RegisterCase/SecretaryInput'
import BusinessLeaderInput from './RegisterCase/BusinessLeaderInput'
import BusinessLeaderHistory from './RegisterCase/BusinessLeaderHistory'
import DocketDatetimeInput from './RegisterCase/DocketDatetimeInput'
import DocketDatetimeHistory from './RegisterCase/DocketDatetimeHistory'
const { confirm } = Modal
class RegisterCase extends Component {
  state = {

  }

  // 处理立案秘书发起呈批数据
  dealAcceptData (data) {
    delete data.secretary
    return Promise.resolve(data)
  }

  // 处理业务处领导呈批数据
  dealAcceptDataTwo (data) {
    delete data.secretary
    delete data.secretaryTutor
    return Promise.resolve(data)
  }

  // 处理立案时间的呈批数据
  dealDocketDatetime (data) {
    const vars = data.vars
    vars.docket_datetime = Math.floor(vars.docket_datetime.valueOf() / 1000)
    return Promise.resolve(data)
  }

  // 呈批表单格式化数据
  beforeSubmit (instance, data) {
    switch (instance.currentStep.step_key) {
      case 'lian01':
        return this.dealAcceptData(data)
      case 'lian02':
        return this.dealAcceptDataTwo(data)
      case 'lian03':
        return this.dealDocketDatetime(data)
      default:
        return data
    }
  }

  // 渲染当前操作步骤线上部分
  renderCurrentStepLineTop (formRef, instance, renderFn) {
    switch (instance.currentStep.step_key) {
      case 'lian01':
        return <SecretaryInput instance={instance} userInfo={this.props.userInfo} caseDetail={this.props.caseDetail} formRef={formRef} />
      case 'lian02':
        return <BusinessLeaderInput instance={instance} userInfo={this.props.userInfo} caseDetail={this.props.caseDetail} formRef={formRef} />
      case 'lian03':
        return <DocketDatetimeInput instance={instance} userInfo={this.props.userInfo} caseDetail={this.props.caseDetail} formRef={formRef} />
      default:
        return renderFn()
    }
  }

  // 渲染历史
  renderHistory (action, renderFn, instance, renderDocument) {
    const key = action.step_key
    const isDisagree = action.opt_add === 'disagree'
    if (key === 'lian01') {
      return <SecretaryHistory key={action.id} userInfo={this.props.userInfo} instance={instance} action={action} />
    } else if (key === 'lian02' && !isDisagree) {
      return <BusinessLeaderHistory key={action.id} userInfo={this.props.userInfo} instance={instance} action={action} />
    } else if (key === 'lian03') {
      return <DocketDatetimeHistory key={action.id} userInfo={this.props.userInfo} instance={instance} action={action} renderDocument={renderDocument} />
    }
    return renderFn(action)
  }

  // 获取立案秘书推荐的秘书
  getSecretaryFormInitialData (instance) {
    const h = instance.history
    if (h.length === 0) {
      return {}
    }
    const { varsMap } = h[h.length - 1]
    return {
      vars: {
        processerid: (varsMap.processerid_recommend || {}).value,
        processer: (varsMap.processer_recommend || {}).value,
        docket_datetime: moment()
      },
      secretary: (varsMap.processer_recommend || {}).value
    }
  }

  // 获取立案时间
  getDocketDatetimeInitialData (instance) {
    const h = instance.history
    if (h.length === 0) {
      return {}
    }
    return {
      vars: {
        docket_datetime: moment()
      }
    }
  }

  // 获取表单初始化数据
  getFormInitialData (instance) {
    switch (instance.currentStep.step_key) {
      case 'lian02':
        return this.getSecretaryFormInitialData(instance)
      case 'lian03':
        return this.getDocketDatetimeInitialData(instance)
      default:
        return {}
    }
  }

  // 判断当事人的证件信息是否完善
  isPartyInfoFull () {
    const { applicants, respondents } = this.props.caseDetail || {}
    const list = [...applicants, ...respondents].filter(li => li.status)
    for (let i = 0; i < list.length; i++) {
      const li = list[i]
      if (!li.license) {
        return false
      }
    }
    if (list.length === 0) {
      return false
    }
    return true
  }

  // 判断是否要去完善信息
  confirmToInfo () {
    if (!this.props.caseDetail.id) {
      return setTimeout(() => {
        this.confirmToInfo()
      }, 100)
    }
    const isCaseFull = this.props.caseDetail.cause_action
    const isPartyFull = this.isPartyInfoFull()
    const ms = []
    if (!isCaseFull) {
      ms.push('案件信息')
    }
    if (!isPartyFull) {
      ms.push('当事人证件信息')
    }
    if (!isCaseFull || !isPartyFull) {
      confirm({
        icon: <ExclamationCircleOutlined />,
        content: `请先完善${ms.join('和')}`,
        okText: '去完善信息',
        cancelText: '取消',
        onOk: () => {
          this.props.toFullInfo()
        },
        onCancel: () => {
          this.props.close()
        }
      })
    }
  }

  componentDidMount () {
    this.confirmToInfo()
  }

  render () {
    if (!this.props.caseDetail.id) {
      return null
    }
    const isCaseFull = this.props.caseDetail.cause_action
    const isPartyFull = this.isPartyInfoFull()
    const ms = []
    if (!isCaseFull) {
      ms.push('案件信息')
    }
    if (!isPartyFull) {
      ms.push('当事人证件信息')
    }
    if (!isCaseFull || !isPartyFull) {
      return (
        <Alert
          message={`请先完善${ms.join('和')}`}
          type='warning'
          showIcon
        />
      )
    }
    return (
      <div>
        <Approve
          caseDetail={this.props.caseDetail}
          flowKey='lian'
          afterAction={(instance, action) => this.props.refreshCaseData()}
          renderCurrentStepLineTop={(...params) => this.renderCurrentStepLineTop(...params)}
          beforeSubmit={(...params) => this.beforeSubmit(...params)}
          renderHistory={(h, renderFn, instance, renderDocument) => this.renderHistory(h, renderFn, instance, renderDocument)}
          initialCurrentStepFormData={instance => this.getFormInitialData(instance)}
          creatable={this.props.editable}
        />
      </div>
    )
  }
}

RegisterCase.propTypes = {
  caseDetail: PropTypes.object,
  // active: PropTypes.bool,
  refreshCaseData: PropTypes.func,
  editable: PropTypes.bool
  // fileList: PropTypes.array
  // getFileList: PropTypes.func
}
RegisterCase.defaultProps = {
  caseDetail: {},
  active: false,
  refreshCaseData: () => {},
  editable: false,
  fileList: [],
  getFileList: () => {}
}

const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {
    addWindow: (i) => dispatch(addWindow(i))
  }
})

export default connect(mapState, mapDispatch)(RegisterCase)
